<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="设备名称" prop="assetName">
        <el-input
          v-model="queryParams.assetName"
          placeholder="请输入设备/物资名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="资产编号" prop="assetNumber">
        <el-input
          v-model="queryParams.assetNumber"
          placeholder="请输入资产编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="型号规格" prop="modelSpec">
        <el-input
          v-model="queryParams.modelSpec"
          placeholder="请输入型号规格"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['equ:asset:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['equ:asset:edit']"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['equ:asset:remove']"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['equ:asset:export']"
        >导出
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="assetList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="资产设备id" align="center" prop="assetId"/>
      <el-table-column label="设备/物资名称" align="center" prop="assetName"/>
      <el-table-column label="资产唯一编号" align="center" prop="assetNumber"/>
      <el-table-column label="资产类型" align="center" prop="assetType"/>
      <el-table-column label="型号规格" align="center" prop="modelSpec"/>
      <el-table-column label="资产状态" align="center" prop="assetStatus"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleView(scope.row)"
            v-hasPermi="['equ:asset:view']"
          >查看
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['equ:asset:edit']"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['equ:asset:remove']"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
    <!-- 添加或修改资产设备对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="900px" append-to-body>
      <!-- 查看模式专用导航栏 -->
      <div v-if="isView" class="dialog-nav">
        <el-tabs v-model="activeTab" type="card" @tab-click="handleTabChange" :key="'tabs-' + activeTab">
          <el-tab-pane label="基础信息" name="basic"></el-tab-pane>
          <el-tab-pane label="移动信息" name="move"></el-tab-pane>
          <el-tab-pane label="入库信息" name="storage"></el-tab-pane>
          <el-tab-pane label="报废信息" name="scrap"></el-tab-pane>
          <el-tab-pane label="维修信息" name="repair"></el-tab-pane>
        </el-tabs>
      </div>

      <el-form :model="form" :rules="rules" ref="formRef" label-width="120px" class="view-form">
        <!-- 基础信息模块 -->
        <el-row :gutter="20" v-if="!isView || activeTab === 'basic'">
          <el-col :span="12">
            <el-form-item label="资产设备id" prop="assetId">
              <el-input v-model="form.assetId" disabled v-if="form.assetId"/>
              <el-input v-model="form.assetId" v-else disabled placeholder="新增后自动生成"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="设备/物资名称" prop="assetName">
              <el-input v-model="form.assetName" placeholder="请输入设备/物资名称" :disabled="isView"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="资产唯一编号" prop="assetNumber">
              <el-input v-model="form.assetNumber" placeholder="请输入资产唯一编号" :disabled="isView"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="品牌" prop="assetBrand">
              <el-select v-model="form.assetBrand" placeholder="请选择品牌" clearable :disabled="isView">
                <el-option
                  v-for="brandName in brandNameList"
                  :key="brandName"
                  :label="brandName"
                  :value="brandName"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="资产类型" prop="assetType">
              <el-input v-model="form.assetType" placeholder="请输入资产类型" :disabled="isView"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="型号规格" prop="modelSpec">
              <el-input v-model="form.modelSpec" placeholder="请输入型号规格" :disabled="isView"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="生产批号" prop="batchNumber">
              <el-input v-model="form.batchNumber" placeholder="请输入生产批号" :disabled="isView"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="生产厂家" prop="manufacturer">
              <el-input v-model="form.manufacturer" placeholder="请输入生产厂家" :disabled="isView"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="供应商名称" prop="supplier">
              <el-input v-model="form.supplier" placeholder="请输入供应商名称" :disabled="isView"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="检测报告" prop="checkReport">
              <file-upload v-model="form.checkReport" :disabled="isView"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="产品合格证" prop="certificate">
              <file-upload v-model="form.certificate" :disabled="isView"/>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="包装照片" prop="packageImage">
              <image-upload v-model="form.packageImage" v-if="open && !isView"/>
              <div v-else-if="form.packageImage" class="view-image">
                <image-preview :src="form.packageImage" :width="100" :height="100"/>
              </div>
              <span v-else>无照片</span>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="采购合同编号" prop="contractNo">
              <el-input v-model="form.contractNo" placeholder="请输入采购合同编号" :disabled="isView"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="发票编号" prop="invoiceNumber">
              <el-input v-model="form.invoiceNumber" placeholder="请输入发票编号" :disabled="isView"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="是否含税" prop="isTax">
              <el-select v-model="form.isTax" placeholder="请选择是否含税" clearable :disabled="isView">
                <el-option label="含税" value="含税"></el-option>
                <el-option label="不含税" value="不含税"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="到货日期" prop="arrivalDate">
              <el-date-picker clearable
                              v-model="form.arrivalDate"
                              type="date"
                              value-format="yyyy-MM-dd"
                              placeholder="请选择到货日期"
                              :disabled="isView">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="运输单位" prop="transportUnit">
              <el-input v-model="form.transportUnit" placeholder="请输入运输单位" :disabled="isView"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="运输单号" prop="transportNo">
              <el-input v-model="form.transportNo" placeholder="请输入运输单号" :disabled="isView"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="购置金额" prop="purchaseAmount">
              <el-input v-model="form.purchaseAmount" placeholder="请输入购置金额" :disabled="isView"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="规定使用年限" prop="serviceLife">
              <el-input v-model="form.serviceLife" placeholder="请输入规定使用年限" :disabled="isView"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="质保开始日期" prop="warrantyStartTime">
              <el-date-picker clearable
                              v-model="form.warrantyStartTime"
                              type="date"
                              value-format="yyyy-MM-dd"
                              placeholder="请选择日期"
                              :disabled="isView">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="质保结束日期" prop="warrantyEndTime">
              <el-date-picker clearable
                              v-model="form.warrantyEndTime"
                              type="date"
                              value-format="yyyy-MM-dd"
                              placeholder="请选择日期"
                              :disabled="isView">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="接收科室" prop="acceptDept">
              <el-input v-model="form.acceptDept" placeholder="请输入接收科室" :disabled="isView"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="当前使用科室" prop="useDept">
              <el-input v-model="form.useDept" placeholder="请输入当前使用科室" :disabled="isView"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="当前存放地点" prop="storageLocation">
              <el-input v-model="form.storageLocation" placeholder="请输入当前存放地点" :disabled="isView"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="入库数量" prop="num">
              <el-input v-model="form.num" placeholder="请输入入库数量(默认1，耗材会大于1)" :disabled="isView"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="购置日期" prop="purchaseDate">
              <el-date-picker clearable
                              v-model="form.purchaseDate"
                              type="date"
                              value-format="yyyy-MM-dd"
                              placeholder="请选择购置日期"
                              :disabled="isView">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="累计折旧金额" prop="accumulatedDepreciation">
              <el-input v-model="form.accumulatedDepreciation" placeholder="请输入累计折旧金额" :disabled="isView"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="资产账面净值" prop="bookValue">
              <el-input v-model="form.bookValue" placeholder="请输入资产账面净值" :disabled="isView"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="资产状态" prop="assetStatus">
              <el-input v-model="form.assetStatus" placeholder="请输入资产状态" :disabled="isView"/>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="其他信息" prop="otherInfo">
              <el-table :data="otherInfoList" style="width: 100%" border>
                <el-table-column label="属性名" width="200">
                  <template slot-scope="scope">
                    <el-input v-model="scope.row.key" placeholder="请输入属性名" @blur="checkDuplicateKey(scope.$index)"
                              :disabled="isView"/>
                  </template>
                </el-table-column>
                <el-table-column label="属性值">
                  <template slot-scope="scope">
                    <el-input v-model="scope.row.value" placeholder="请输入属性值" :disabled="isView"/>
                  </template>
                </el-table-column>
                <el-table-column label="操作" width="100" align="center" v-if="!isView">
                  <template slot-scope="scope">
                    <el-button size="mini" type="danger" icon="el-icon-delete"
                               @click="removeOtherInfoRow(scope.$index)"></el-button>
                  </template>
                </el-table-column>
              </el-table>
              <div style="margin-top: 10px" v-if="!isView">
                <el-button type="primary" size="mini" icon="el-icon-plus" @click="addOtherInfoRow">添加属性</el-button>
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" type="textarea" :rows="3" placeholder="请输入备注" :disabled="isView"/>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 移动信息模块 (使用展开行和JSON编辑器) -->
        <el-row :gutter="20" v-if="isView && activeTab === 'move'" :key="'move-' + activeTab">
          <el-col :span="24">
            <el-card shadow="hover">
              <div slot="header" class="clearfix">
                <span>移动记录列表（共{{ moveRecordList.length }}条）</span>
              </div>
              <el-table :data="moveRecordList" style="width: 100%" border v-loading="moveLoading">
                <el-table-column type="expand">
                  <template slot-scope="props">
                    <vue-json-editor
                      v-model="parsedMoveDetails[props.$index]"
                      :options="jsonEditorOptions"
                      class="json-editor clean-json-editor"
                    />
                  </template>
                </el-table-column>
                <el-table-column label="序号" type="index" width="60" align="center"></el-table-column>
                <el-table-column label="移动时间" prop="finishTime" width="180" align="center"></el-table-column>
                <el-table-column label="移动类型" prop="moveType" align="center"></el-table-column>
              </el-table>
              <div v-if="moveRecordList.length === 0 && !moveLoading" class="no-record">暂无移动记录</div>
            </el-card>
          </el-col>
        </el-row>

        <!-- 入库信息模块 (使用展开行和JSON编辑器) -->
        <el-row :gutter="20" v-if="isView && activeTab === 'storage'" :key="'storage-' + activeTab">
          <el-col :span="24">
            <el-card shadow="hover">
              <div slot="header" class="clearfix">
                <span>入库记录列表（共{{ storageRecordList.length }}条）</span>
              </div>
              <el-table :data="storageRecordList" style="width: 100%" border v-loading="storageLoading">
                <el-table-column type="expand">
                  <template slot-scope="props">
                    <vue-json-editor
                      v-model="parsedStorageDetails[props.$index]"
                      :options="jsonEditorOptions"
                      class="json-editor clean-json-editor"
                    />
                  </template>
                </el-table-column>
                <el-table-column label="序号" type="index" width="60" align="center"></el-table-column>
                <el-table-column label="入库时间" prop="finishTime" width="180" align="center"></el-table-column>
                <el-table-column label="验收最终状态" prop="acceptanceStatus" align="center"></el-table-column>
                <el-table-column label="备注" prop="remark" align="center"></el-table-column>
              </el-table>
              <div v-if="storageRecordList.length === 0 && !storageLoading" class="no-record">暂无入库记录</div>
            </el-card>
          </el-col>
        </el-row>

        <!-- 报废信息模块 (使用展开行和JSON编辑器) -->
        <el-row :gutter="20" v-if="isView && activeTab === 'scrap'" :key="'scrap-' + activeTab">
          <el-col :span="24">
            <el-card shadow="hover">
              <div slot="header" class="clearfix">
                <span>报废记录列表（共{{ scrapRecordList.length }}条）</span>
              </div>
              <el-table :data="scrapRecordList" style="width: 100%" border v-loading="scrapLoading">
                <el-table-column type="expand">
                  <template slot-scope="props">
                    <vue-json-editor
                      v-model="parsedScrapDetails[props.$index]"
                      :options="jsonEditorOptions"
                      class="json-editor clean-json-editor"
                    />
                  </template>
                </el-table-column>
                <el-table-column label="序号" type="index" width="60" align="center"></el-table-column>
                <el-table-column label="报废时间" prop="scrapDate" width="180" align="center"></el-table-column>
                <el-table-column label="备注" prop="remark" align="center"></el-table-column>
              </el-table>
              <div v-if="scrapRecordList.length === 0 && !scrapLoading" class="no-record">暂无报废记录</div>
            </el-card>
          </el-col>
        </el-row>

        <!-- 维修信息模块 (使用展开行和JSON编辑器) -->
        <el-row :gutter="20" v-if="isView && activeTab === 'repair'" :key="'repair-' + activeTab">
          <el-col :span="24">
            <el-card shadow="hover">
              <div slot="header" class="clearfix">
                <span>维修记录列表（共{{ repairRecordList.length }}条）</span>
              </div>
              <el-table :data="repairRecordList" style="width: 100%" border v-loading="repairLoading">
                <el-table-column type="expand">
                  <template slot-scope="props">
                    <vue-json-editor
                      v-model="parsedRepairDetails[props.$index]"
                      :options="jsonEditorOptions"
                      class="json-editor clean-json-editor"
                    />
                  </template>
                </el-table-column>
                <el-table-column label="序号" type="index" width="60" align="center"></el-table-column>
                <el-table-column label="维修时间" prop="createTime" width="180" align="center"></el-table-column>
                <el-table-column label="备注" prop="remark" align="center"></el-table-column>
                <el-table-column label="维修状态" prop="orderStatus" align="center"></el-table-column>
              </el-table>
              <div v-if="repairRecordList.length === 0 && !repairLoading" class="no-record">暂无维修记录</div>
            </el-card>
          </el-col>
        </el-row>
      </el-form>

      <!--  去掉查看模式的取消按钮 -->
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm" v-if="!isView">确 定</el-button>
        <el-button @click="cancel" v-if="!isView">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import VueJsonEditor from 'vue-json-editor';
import {listAsset, getAsset, delAsset, addAsset, updateAsset} from "@/api/equ/asset";
import {getAllBrandName} from "@/api/equ/brand";
import {listMoves} from "@/api/equ/move";
import {listStockins} from "@/api/equ/stockin";
import {listScraps} from "@/api/equ/scrap";
import {listRepairs} from "@/api/equ/repair";

export default {
  name: "Asset",
  components: { VueJsonEditor },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 各模块列表加载状态
      moveLoading: false,
      storageLoading: false,
      scrapLoading: false,
      repairLoading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 资产设备表格数据
      assetList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 是否是查看模式
      isView: false,
      // 当前激活的标签页（查看模式用）
      activeTab: "basic",
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        assetName: null,
        assetNumber: null,
        assetType: null,
        modelSpec: null,
        manufacturer: null,
        packageImage: null,
        supplier: null,
        contractNo: null,
        invoiceNumber: null,
        isTax: null,
        purchaseAmount: null,
        serviceLife: null,
        warrantyPeriod: null,
        acceptDept: null,
        useDept: null,
        storageLocation: null,
        num: null,
        purchaseDate: null,
        accumulatedDepreciation: null,
        bookValue: null,
        assetStatus: null,
        otherInfo: null,
      },
      // 表单参数
      form: {
        assetId: null,
        assetName: null,
        assetNumber: null,
        assetType: null,
        modelSpec: null,
        manufacturer: null,
        packageImage: null,
        supplier: null,
        contractNo: null,
        invoiceNumber: null,
        isTax: null,
        purchaseAmount: null,
        serviceLife: null,
        warrantyPeriod: null,
        acceptDept: null,
        useDept: null,
        storageLocation: null,
        num: null,
        purchaseDate: null,
        accumulatedDepreciation: null,
        bookValue: null,
        assetStatus: null,
        otherInfo: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null,
        assetBrand: null,
        arrivalDate: null,
        transportUnit: null,
        transportNo: null,
        warrantyStartTime: null,
        warrantyEndTime: null,
        batchNumber: null,
        checkReport: null,
        certificate: null
      },
      // 其他信息动态表单（基础信息模块，支持编辑）
      otherInfoList: [{key: '', value: ''}],
      // 品牌名称列表
      brandNameList: [],
      // 各模块多条记录列表（存储概要信息）
      moveRecordList: [],
      storageRecordList: [],
      scrapRecordList: [],
      repairRecordList: [],
      // 解析后的详情数据，供JSON编辑器使用
      parsedMoveDetails: [],
      parsedStorageDetails: [],
      parsedScrapDetails: [],
      parsedRepairDetails: [],
      // JSON编辑器配置
      jsonEditorOptions: {
        mode: 'view',  // 查看模式，不可编辑
        expanded: true,
        showBtn: false,
        indentation: 2,
        mainMenuBar: false
      },
      // 表单校验
      rules: {
        assetName: [{required: true, message: "设备/物资名称不能为空", trigger: "blur"}],
        assetNumber: [{required: true, message: "资产唯一编号不能为空", trigger: "blur"}],
        modelSpec: [{required: true, message: "型号规格不能为空", trigger: "blur"}]
      }
    };
  },
  created() {
    this.getList();
    this.fetchBrandNames();
  },
  methods: {
    /** 查询资产设备列表 */
    getList() {
      this.loading = true;
      listAsset(this.queryParams).then(response => {
        this.assetList = response.rows;
        this.total = response.total;
      }).catch(error => {
        console.error('查询资产列表失败：', error);
      }).finally(() => {
        this.loading = false;
      });
    },
    /** 查询品牌名称列表 */
    fetchBrandNames() {
      getAllBrandName().then(response => {
        if (response.code === 200) {
          this.brandNameList = response.data || [];
        } else {
          this.$modal.msgError(`获取品牌失败：${response.msg}`);
          this.brandNameList = [];
        }
      }).catch(error => {
        console.error("品牌接口调用异常：", error);
        this.$modal.msgError("获取品牌列表失败，请刷新重试");
        this.brandNameList = [];
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.isView = false;
      this.activeTab = "basic";
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        assetId: null,
        assetName: null,
        assetNumber: null,
        assetType: null,
        modelSpec: null,
        manufacturer: null,
        packageImage: null,
        supplier: null,
        contractNo: null,
        invoiceNumber: null,
        isTax: null,
        purchaseAmount: null,
        serviceLife: null,
        warrantyPeriod: null,
        acceptDept: null,
        useDept: null,
        storageLocation: null,
        num: null,
        purchaseDate: null,
        accumulatedDepreciation: null,
        bookValue: null,
        assetStatus: null,
        otherInfo: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null,
        assetBrand: null,
        arrivalDate: null,
        transportUnit: null,
        transportNo: null,
        warrantyStartTime: null,
        warrantyEndTime: null,
        batchNumber: null,
        checkReport: null,
        certificate: null
      };
      // 重置动态列表
      this.otherInfoList = [{key: '', value: ''}];
      // 重置各模块记录列表和解析后的数据
      this.moveRecordList = [];
      this.storageRecordList = [];
      this.scrapRecordList = [];
      this.repairRecordList = [];
      this.parsedMoveDetails = [];
      this.parsedStorageDetails = [];
      this.parsedScrapDetails = [];
      this.parsedRepairDetails = [];

      this.$refs.formRef?.clearValidate();
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.$refs.queryForm.resetFields();
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.assetId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.isView = false;
      this.title = "添加资产设备";
      this.fetchBrandNames();
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const assetId = row.assetId || this.ids
      getAsset(assetId).then(response => {
        this.form = response.data;
        this.parseOtherInfoToList();
        this.open = true;
        this.isView = false;
        this.title = "修改资产设备";
        this.fetchBrandNames();
      });
    },
    /** 查看详情按钮操作（加载基础信息+各模块多条记录） */
    handleView(row) {
      this.reset();
      const assetId = row.assetId;
      getAsset(assetId).then(response => {
        this.form = response.data;
        this.parseOtherInfoToList();
        this.open = true;
        this.isView = true;
        this.activeTab = "basic";
        this.title = "查看资产设备详情";
      });
      // 加载所有模块记录
      this.fetchMoveRecords(assetId);
      this.fetchStorageRecords(assetId);
      this.fetchScrapRecords(assetId);
      this.fetchRepairRecords(assetId);
    },
    /** 标签页切换事件 */
    handleTabChange(tab) {
      this.activeTab = tab.name;
      const assetId = this.form.assetId;
      if (!assetId) return; // assetId为空时不调用接口

      // 根据切换到的标签页加载对应数据
      switch (this.activeTab) {
        case "move":
          if (this.moveRecordList.length === 0) this.fetchMoveRecords(assetId);
          break;
        case "storage":
          if (this.storageRecordList.length === 0) this.fetchStorageRecords(assetId);
          break;
        case "scrap":
          if (this.scrapRecordList.length === 0) this.fetchScrapRecords(assetId);
          break;
        case "repair":
          if (this.repairRecordList.length === 0) this.fetchRepairRecords(assetId);
          break;
        default:
          break;
      }
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["formRef"].validate(valid => {
        if (valid) {
          // 将动态表单转换为otherInfo JSON字符串
          const otherInfoStr = this.convertOtherInfoListToString();
          if (otherInfoStr === null) return;
          this.form.otherInfo = otherInfoStr;

          const request = this.form.assetId ? updateAsset : addAsset;
          request(this.form).then(() => {
            this.$modal.msgSuccess(this.form.assetId ? "修改成功" : "新增成功");
            this.open = false;
            this.getList();
          }).catch(error => {
            console.error('提交失败：', error);
            this.$modal.msgError('操作失败，请重试');
          });
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const assetIds = row.assetId || this.ids;
      this.$modal.confirm(`是否确认删除资产设备编号为 ${assetIds} 的数据项？`).then(function () {
        return delAsset(assetIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('equ/asset/export', {
        ...this.queryParams
      }, `asset_${new Date().getTime()}.xlsx`)
    },

    /** 解析otherInfo为动态表单（基础信息模块） */
    parseOtherInfoToList() {
      if (this.form.otherInfo) {
        try {
          const infoObj = typeof this.form.otherInfo === 'string' ? JSON.parse(this.form.otherInfo) : this.form.otherInfo;
          this.otherInfoList = infoObj.map(item => {
            const key = Object.keys(item)[0];
            return {key, value: item[key]};
          });
        } catch (e) {
          console.error('解析otherInfo失败:', e);
          this.otherInfoList = [{key: '', value: ''}];
        }
      } else {
        this.otherInfoList = [{key: '', value: ''}];
      }
    },

    /** 基础信息模块：添加一行其他信息 */
    addOtherInfoRow() {
      const hasEmptyKey = this.otherInfoList.some(item => !item.key.trim());
      if (hasEmptyKey) {
        this.$modal.msgWarning("请先填写当前空的属性名");
        return;
      }
      this.otherInfoList.push({key: '', value: ''});
    },

    /** 基础信息模块：删除一行其他信息 */
    removeOtherInfoRow(index) {
      if (this.otherInfoList.length <= 1) {
        this.$modal.msgWarning("至少保留一行数据");
        return;
      }
      this.otherInfoList.splice(index, 1);
    },

    /** 基础信息模块：检查键名是否重复 */
    checkDuplicateKey(currentIndex) {
      const currentKey = this.otherInfoList[currentIndex].key.trim();
      if (!currentKey) return;

      const duplicateIndex = this.otherInfoList.findIndex((item, index) =>
        index !== currentIndex && item.key.trim() === currentKey);

      if (duplicateIndex !== -1) {
        this.$modal.msgWarning(`属性名"${currentKey}"已存在，请修改为其他名称`);
        this.otherInfoList[currentIndex].key = '';
      }
    },

    /** 基础信息模块：将otherInfoList转换为JSON字符串 */
    convertOtherInfoListToString() {
      if (this.otherInfoList.length === 0) return '';

      const filteredList = this.otherInfoList.filter(item => item.key.trim() || item.value.trim());
      if (filteredList.length === 0) return '';

      const keys = filteredList.map(item => item.key.trim());
      const uniqueKeys = [...new Set(keys)];
      if (keys.length !== uniqueKeys.length) {
        this.$modal.msgError("存在重复的属性名，请检查后重新提交");
        return null;
      }

      const infoObj = filteredList.map(item => ({[item.key.trim()]: item.value.trim()}));
      return JSON.stringify(infoObj);
    },

    /** 安全解析JSON字符串 */
    safeParseJSON(jsonString) {
      if (!jsonString || typeof jsonString !== 'string') {
        return {};
      }
      try {
        return JSON.parse(jsonString);
      } catch (e) {
        console.error('JSON解析失败：', e, '原始字符串：', jsonString);
        return { error: '解析失败', raw_data: jsonString };
      }
    },

    // 以下为各模块多条记录相关方法
    /** 加载移动记录列表 */
    fetchMoveRecords(assetId) {
      this.moveLoading = true;
      listMoves(assetId)
        .then(response => {
          this.moveRecordList = response.rows || [];
          // 解析每条记录的JSON字段，准备给编辑器使用
          this.parsedMoveDetails = this.moveRecordList.map(record => {
            return {
              ...record,
              moveBasis: this.safeParseJSON(record.moveBasis),
              executeInfo: this.safeParseJSON(record.executeInfo),
              moveAfterStatus: this.safeParseJSON(record.moveAfterStatus),
            };
          });
        })
        .catch(error => {
          console.error("加载移动记录失败：", error);
          this.$modal.msgError("加载移动记录失败，请刷新重试");
          this.moveRecordList = [];
          this.parsedMoveDetails = [];
        })
        .finally(() => {
          this.moveLoading = false;
        });
    },

    /** 加载入库记录列表 */
    fetchStorageRecords(assetId) {
      this.storageLoading = true;
      listStockins(assetId)
        .then(response => {
          this.storageRecordList = response.rows || [];
          // 解析每条记录的JSON字段
          this.parsedStorageDetails = this.storageRecordList.map(record => {
            return {
              ...record,
              approvalInfo: this.safeParseJSON(record.approvalInfo),
              arrivalInfo: this.safeParseJSON(record.arrivalInfo),
              packageCheck: this.safeParseJSON(record.packageCheck),
              quantityCheck: this.safeParseJSON(record.quantityCheck),
              docCheck: this.safeParseJSON(record.docCheck),
              qualityCheck: this.safeParseJSON(record.qualityCheck),
              approvalRecord: this.safeParseJSON(record.approvalRecord),
            };
          });
        })
        .catch(error => {
          console.error("加载入库记录失败：", error);
          this.$modal.msgError("加载入库记录失败，请刷新重试");
          this.storageRecordList = [];
          this.parsedStorageDetails = [];
        })
        .finally(() => {
          this.storageLoading = false;
        });
    },

    /** 加载报废记录列表 */
    fetchScrapRecords(assetId) {
      this.scrapLoading = true;
      listScraps(assetId)
        .then(response => {
          this.scrapRecordList = response.rows || [];
          // 解析每条记录的JSON字段
          this.parsedScrapDetails = this.scrapRecordList.map(record => {
            return {
              ...record,
              scrapBasis: this.safeParseJSON(record.scrapBasis),
              approvalSummary: this.safeParseJSON(record.approvalSummary),
              disposalInfo: this.safeParseJSON(record.disposalInfo),
            };
          });
        })
        .catch(error => {
          console.error("加载报废记录失败：", error);
          this.$modal.msgError("加载报废记录失败，请刷新重试");
          this.scrapRecordList = [];
          this.parsedScrapDetails = [];
        })
        .finally(() => {
          this.scrapLoading = false;
        });
    },

    /** 加载维修记录列表 */
    fetchRepairRecords(assetId) {
      this.repairLoading = true;
      listRepairs(assetId)
        .then(response => {
          this.repairRecordList = response.rows || [];
          // 解析每条记录的JSON字段
          this.parsedRepairDetails = this.repairRecordList.map(record => {
            return {
              ...record,
              faultInfo: this.safeParseJSON(record.faultInfo),
              repairExec: this.safeParseJSON(record.repairExec),
              repairCheck: this.safeParseJSON(record.repairCheck),
            };
          });
        })
        .catch(error => {
          console.error("加载维修记录失败：", error);
          this.$modal.msgError("加载维修记录失败，请刷新重试");
          this.repairRecordList = [];
          this.parsedRepairDetails = [];
        })
        .finally(() => {
          this.repairLoading = false;
        });
    },
  }
};
</script>

<style scoped>
.view-form {
  max-height: 60vh;
  overflow-y: auto;
  padding-right: 10px;
}
.view-form::-webkit-scrollbar { width: 8px; }
.view-form::-webkit-scrollbar-track { background: #f1f1f1; }
.view-form::-webkit-scrollbar-thumb { background: #c0c4cc; border-radius: 4px; }
.view-form::-webkit-scrollbar-thumb:hover { background: #909399; }

.view-image {
  display: inline-block;
  border: 1px solid #eee;
  padding: 5px;
  border-radius: 4px;
}

/* 导航栏样式优化 */
.dialog-nav {
  margin-bottom: 15px;
}

.el-tabs--card > .el-tabs__header {
  border-bottom: 1px solid #e6e6e6;
}

.el-tabs--card > .el-tabs__header .el-tabs__item {
  border-radius: 4px 4px 0 0;
  margin-right: 8px;
  padding: 10px 20px;
}

.el-tabs--card > .el-tabs__header .el-tabs__item.is-active {
  background-color: #fff;
  border-bottom-color: #fff;
  font-weight: 500;
}

/* 禁用状态样式优化 */
.el-input.is-disabled .el-input__inner,
.el-select.is-disabled .el-select__inner,
.el-date-picker.is-disabled .el-input__inner {
  background-color: #f5f7fa;
  color: #666;
  cursor: not-allowed;
}

.no-record {
  text-align: center;
  padding: 30px;
  color: #999;
  font-size: 14px;
}

.el-card {
  margin-bottom: 15px;
}

.el-table .el-table__row:hover {
  cursor: pointer;
}

/* JSON编辑器样式 */
.json-editor {
  min-height: 200px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
}
.clean-json-editor >>> .jsoneditor-menu,
.clean-json-editor >>> .jsoneditor-search,
.clean-json-editor >>> .jsoneditor-dragarea {
  display: none !important;
}
.clean-json-editor >>> .jsoneditor {
  border: none !important;
}
</style>
